// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:heyangkuaidai/BussinessModule/BussinessToast/PublicAssignedToOrganToast.dart';
import 'package:heyangkuaidai/BussinessModule/BussinessToast/PublicWarmInputToast.dart';
import 'package:heyangkuaidai/BussinessModule/BussinessToast/PublicQRToast.dart';
import 'package:heyangkuaidai/BussinessModule/BussinessToast/PublicSuccessResultToast.dart';
import 'package:heyangkuaidai/BussinessModule/BussinessToast/PublicFailResultToast.dart';
import 'package:heyangkuaidai/BussinessModule/BussinessToast/PublicWarmToast.dart';
import 'package:heyangkuaidai/BussinessModule/BussinessToast/QRScanPage.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'dart:convert' as convert;
import 'package:flutter/material.dart';
import 'package:amap_location/amap_location.dart';
import 'package:easy_alert/easy_alert.dart';
void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await AMapLocationClient.startup(new AMapLocationOption( desiredAccuracy:CLLocationAccuracy.kCLLocationAccuracyHundredMeters  ));
  runApp(
      MaterialApp(
          debugShowCheckedModeBanner: false,
          home: WebViewExample(),
          routes: <String, WidgetBuilder> {
            // 这里可以定义静态路由，不能传递参数
            "/QRScanPage":(context) =>QRScanPage(),
          }
      )
  );
}

const String kNavigationExamplePage = '''
<!DOCTYPE html><html>
<head><title>Navigation Delegate Example</title></head>
<body>
<p>
The navigation delegate is set to block navigation to the youtube website.
</p>
<ul>
<ul><a href="https://www.youtube.com/">https://www.youtube.com/</a></ul>
<ul><a href="https://www.google.com/">https://www.google.com/</a></ul>
</ul>
</body>
</html>
''';

class WebViewExample extends StatefulWidget {
  @override
  _WebViewExampleState createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<WebViewExample> {
  final Completer<WebViewController> _controller = Completer<WebViewController>();
  WebViewController _webViewController ;
  AMapLocation _loc;
  String HtmlStr ="";
  var tellerName;
  var tellerNo;
  bool startload =false;
  static const platform = const MethodChannel('app.channel.shared.data');

  Future exit() async {
    try {
      await platform.invokeMethod("exit");
    } on PlatformException catch (e) {
      print(e.toString());
    }
    return ;
  }
  Future<String> getIntentText() async {
    var str;
    try {
      str = await platform.invokeMethod("getIntentText");
      tellerName = str.split("/")[0];
      tellerNo =str.split("/")[1];

      // HtmlStr ="https://ecredit-wx.linkustech-linkus.com/hnrcc-pad/h5/pad/henyang_pad/index.html#/index?custId=$tellerNo";
      HtmlStr ="https://11.1.9.26:8002/hyhtml/h5/pad/hengyang_pad/index.html#/index?custId=$tellerNo";
      setState(() {
        startload =true;
      });

    } on PlatformException catch (e) {
      print(e.toString());
    }
    return str;
  }
  void _checkPersmission() async {
    PermissionStatus permission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.locationWhenInUse);
    print('permission$permission');
    if (permission ==PermissionStatus.denied) {
      final List<PermissionGroup> permissions = <PermissionGroup>[PermissionGroup.locationWhenInUse];
      final Map<PermissionGroup, PermissionStatus> permissionRequestResult =
      await PermissionHandler().requestPermissions(permissions);
      permission = permissionRequestResult[PermissionGroup.locationWhenInUse];
      if (permission != PermissionStatus.granted) {
        Alert.alert(context, title: "申请定位权限失败");
        return;
      }
    }
    _loc = await AMapLocationClient.getLocation(true);
    String locPath =_loc.formattedAddress;
    await _webViewController.evaluateJavascript(
        'getloc("$locPath")');
  }
  @override
  void initState() {
    super.initState();
    getIntentText();
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();

  }
  Widget inputWidget(){
    return Container(
      height:ScreenUtil().setWidth(42),
      width: ScreenUtil().setWidth(281),
      child: TextField(
        textAlignVertical: TextAlignVertical.bottom,
        decoration: InputDecoration(
          fillColor: Color(0xffffffff),
          filled: true,
          border:OutlineInputBorder(borderSide: BorderSide.none),
          hintText: '请输入url链接',
        ),
        style: TextStyle(color: Color(0xff333333),fontSize: ScreenUtil().setSp(18),),textAlign: TextAlign.left,
        //文本内容改变时回调
        onChanged: (text) {
          print('文本内容改变时回调 $text');
          // chooseCallback(text);
          setState(() {
            HtmlStr =text;
          });

        },
        //内容提交时回调
        onSubmitted: (text) {
          print('内容提交时回调 $text');
        },
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 1024, height: 640, allowFontScaling: true);
    return WillPopScope(child:  Scaffold(
      // appBar: AppBar(
      //   title: const Text('Flutter WebView example'),
      //   // This drop down menu demonstrates that Flutter widgets can be shown over the web view.
      //   actions: <Widget>[
      //    inputWidget(),
      //    InkWell(
      //      onTap: (){
      //        _webViewController.loadUrl(HtmlStr);
      //      },
      //      child: Container(
      //        width: ScreenUtil().setWidth(100),
      //        height: ScreenUtil().setWidth(40),
      //        child: Center(
      //          child:Text("前往") ,
      //        ),
      //     ),
      //    )
      //   ],
      // ),
      // We're using a Builder here so we have a context that is below the Scaffold
      // to allow calling Scaffold.of(context) so we can show a snackbar.
      resizeToAvoidBottomInset:false,
      body: Builder(builder: (BuildContext context) {
        return new Column(
          children: [
            SizedBox(height: MediaQuery.of(context).padding.top,),
            !startload?Container():Container(width: ScreenUtil.screenWidth,
              height:ScreenUtil.screenHeight- MediaQuery.of(context).padding.top,
              color: Colors.blue,
              child:WebView(
                initialUrl:HtmlStr,
                javascriptMode: JavascriptMode.unrestricted,
                onWebViewCreated: (WebViewController webViewController) {
                  _controller.complete(webViewController);
                  _webViewController = webViewController;

                },
                onProgress: (int progress) {
                  print("WebView is loading (progress : $progress%)");
                },
                javascriptChannels: <JavascriptChannel>{
                  _inputToasterJavascriptChannel(context),
                  _successToasterJavascriptChannel(context),
                  _scanJavascriptChannel(context),
                  _takePhotoJavascriptChannel(context),
                  _warmToasterJavascriptChannel(context),
                  _qrToasterJavascriptChannel(context),
                  _failToasterJavascriptChannel(context),
                  _getlocJavascriptChannel(context),
                  _exitJavascriptChannel(context)
                },
                navigationDelegate: (NavigationRequest request) {
                  if (request.url.startsWith('https://www.youtube.com/')) {
                    print('blocking navigation to $request}');
                    return NavigationDecision.prevent;
                  }
                  print('allowing navigation to $request');
                  return NavigationDecision.navigate;
                },
                onPageStarted: (String url) {
                  print('Page started loading: $url');
                },
                onPageFinished: (String url) {
                  print('Page finished loading: $url');
                },
                gestureNavigationEnabled: true,
              ),
            )

          ],
        );

      }),
      // floatingActionButton: favoriteButton(),
    ), onWillPop: () async {
            return false;
        },
    );

  }


  //终止：提示预警
  JavascriptChannel _exitJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'exitToaster',
        onMessageReceived: (JavascriptMessage message) {
          showDialog(context: context, barrierDismissible: false, builder: (context){
            return PublicWarmToast(
              closeCallBack: (){
                Navigator.pop(context);
              },
              positiveCallBack: (){
                Navigator.pop(context);
                exit();

              },
              title: '温馨提示',
              warmTip: "是否退出当前界面？",
            );
            }
          );
        }
    );
  }
  //获取地址
  void _getloc(BuildContext context) async {
    _checkPersmission();
  }
  //地址js调用
  JavascriptChannel _getlocJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'getLocation',
        onMessageReceived: (JavascriptMessage message) {
          _getloc(context);
        }
    );
  }
  //终止弹窗
  void _stopToast(BuildContext context,String content) async {
    // Send a message with the user agent string to the Toaster JavaScript channel we registered
    // with the WebView.
    print("content"+content);
    await _webViewController.evaluateJavascript(
        'onPositivePressEvent("$content")');
  }
  //终止：提示预警
  JavascriptChannel _inputToasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'PublicWarmInputToast',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          showDialog(context: context, barrierDismissible: false, builder: (context){
            return PublicWarmInputToast(
                title: "预警提示",
                warmTip: "确认要终止吗？",
                positiveCallBack: (String text){
                  _stopToast(context,text);
                  Navigator.pop(context);
                },
                closeCallBack: (){
                  Navigator.pop(context);
                }
                );
          });

        }
    );
  }


  //温馨提示确定
  void _warmConfirmToast(BuildContext context) async {
    // Send a message with the user agent string to the Toaster JavaScript channel we registered
    // with the WebView.
    await _webViewController.evaluateJavascript(
        'onWarmPositivePressEvent("content")');
  }

  //温馨提示
  JavascriptChannel _warmToasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'PublicWarmToast',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          showDialog(
              context: context,
              builder: (context){
                return PublicWarmToast(
                  closeCallBack: (){
                    Navigator.pop(context);
                  },
                  positiveCallBack: (){
                    Navigator.pop(context);
                    _warmConfirmToast(context);

                  },
                  title: '预警提示',
                  warmTip: "确认知悉该预警并处理吗？",
                );
              }
          );

        }
    );
  }
  //qrToast
  JavascriptChannel _qrToasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'PublicQRToast',
        onMessageReceived: (JavascriptMessage message) {
          Map <String, dynamic> messageMap = json.decode(message.message.toString());
          // ignore: deprecated_member_use
          showDialog(
              context: context,
              builder: (context){
                return PublicQRToast(
                  nameTip:messageMap["nameTip"] ,
                  phoneTip: messageMap["phoneTip"],
                  validDateTip:messageMap["validDateTip"],
                  messageUrl: messageMap["messageUrl"],
                  closeCallBack: (){
                    Navigator.pop(context);
                  },
                  //'微信公众号营销二维码'
                  title: messageMap["title"],
                );
              }
          );

        }
    );
  }

  //failToast
  JavascriptChannel _failToasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'PublicFailResultToast',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          showDialog(
              context: context,
              builder: (context){
                return PublicFailResultToast(
                  closeCallBack: (){
                    Navigator.pop(context);
                  },
                  title: '兑换结果',
                  warmTip: "兑换失败，无效兑换码",
                );
              }
          );

        }
    );
  }

  //successToast
  JavascriptChannel _successToasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'PublicSuccessResultToast',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          print(message.message.toString());
          Map <String, dynamic> messageMap = json.decode(message.message.toString());
          showDialog(
              context: context,
              builder: (context){
                return PublicSuccessResultToast(
                  title:messageMap["title"],
                  warmTip: "兑换成功，请及时将礼品兑换给客户",
                  infoText: messageMap["infoText"],
                  priceText:messageMap["priceText"],
                  closeCallBack: (){
                    Navigator.pop(context);
                  },
                );
              }
          );

        }
    );
  }
  //扫描结果处理
  void _scanResulHandle(BuildContext context,String content) async {
    // Send a message with the user agent string to the Toaster JavaScript channel we registered
    // with the WebView.
    print("content"+content);
    await _webViewController.evaluateJavascript(
        'ScanResult("$content")');
  }
  //scan
  JavascriptChannel _scanJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'toScan',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          Navigator.push(
            context,
            new MaterialPageRoute(
              builder: (context) => new QRScanPage(),
            ),
          ).then((value) {
            print("-----$value");
            _scanResulHandle(context,value);
          });
     });
  }

  //拍照结果处理
  void _photoResulHandle(BuildContext context,String content) async {
    // Send a message with the user agent string to the Toaster JavaScript channel we registered
    // with the WebView.
    print("content"+content);
    await _webViewController.evaluateJavascript(
        'photoResult("$content")');
  }
  //拍照
  JavascriptChannel _takePhotoJavascriptChannel(BuildContext context) {
    File _image1;
    final picker = ImagePicker();

    Future getImage() async {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.camera);
      print('permission$permission');
      Map<PermissionGroup,
          PermissionStatus> permissions = await PermissionHandler()
          .requestPermissions([PermissionGroup.camera]);
      final pickedFile = await picker.getImage(source: ImageSource.camera);
      PermissionStatus permission1 = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
      await PermissionHandler().requestPermissions([PermissionGroup.storage]);
      ImageProperties properties = await FlutterNativeImage.getImageProperties(pickedFile.path);
      File compressedFile = await FlutterNativeImage.compressImage(pickedFile.path, quality: 80,
          targetWidth: 600,
          targetHeight: (properties.height * 600 / properties.width).round());
      setState(() {
        if (pickedFile != null) {
          _image1 = File(compressedFile.path);
          List<int> test = _image1.readAsBytesSync();
          String test2 = base64Encode(test);
          _photoResulHandle(context,test2);
        } else {
          print('No image selected.');
        }
      });
    }
    return JavascriptChannel(
        name: 'takephoto',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          getImage();

        }
    );
  }

  Widget favoriteButton() {
    return FutureBuilder<WebViewController>(
        future: _controller.future,
        builder: (BuildContext context,
            AsyncSnapshot<WebViewController> controller) {
          if (controller.hasData) {
            return FloatingActionButton(
              onPressed: () async {
                final String url = (await controller.data.currentUrl());
                // ignore: deprecated_member_use
                Scaffold.of(context).showSnackBar(
                  SnackBar(content: Text('Favorited $url')),
                );
              },
              child: const Icon(Icons.favorite),
            );
          }
          return Container();
        });
  }
}

